<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>永辉外卖 - 订单管理</title>
    <script src="js/jquery.js"></script>
    <link href="css/font-awesome.css" rel="stylesheet">
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet">
    <link href="css/default-theme.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/bootstrap-reset.css" rel="stylesheet">
    <style>
        /* 订单状态样式 */
        .status-pending { color: #ffc107; font-weight: bold; }
        .status-paid { color: #0d6efd; font-weight: bold; }
        .status-completed { color: #198754; font-weight: bold; }
        .status-cancelled { color: #dc3545; font-weight: bold; }
        .status-refunded { color: #6c757d; font-weight: bold; }

        /*!* 调试信息样式 *!
        #debugInfo {
            display: none;
            margin-bottom: 15px;
        }*/

        /* 表格样式优化 */
        .table {
            font-size: 14px;
        }
        .table th {
            background-color: #f8f9fa;
            white-space: nowrap;
        }
        .table td {
            vertical-align: middle;
        }

        /* 按钮组样式 */
        .btn-group {
            display: flex;
            gap: 5px;
        }
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        /* 加载动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .spinner {
            width: 3rem;
            height: 3rem;
        }

        /* 批量操作区域 */
        .batch-actions {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }

        /* 查询表单样式 */
        #searchForm .form-control {
            width: auto;
            display: inline-block;
        }
        .m-r-10 {
            margin-right: 10px;
        }
        .m-b-20 {
            margin-bottom: 20px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .table-responsive {
                overflow-x: auto;
            }
            .btn-group {
                flex-direction: column;
            }
            #searchForm .form-control {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body class="sticky-header">
<section>
    <!-- 左侧导航栏保持不变 -->
    <div class="sidebar-left">
        <div class="sidebar-left-info">
            <div class=" search-field"> </div>
            <ul class="nav nav-pills nav-stacked side-navigation">
                <li class="menu-list"> <a href=""><i class="fa fa-drivers-license"></i> <span>ID卡管理</span></a>
                    <ul class="child-list">
                        <li><a href="index.html">卡号管理</a></li>
                    </ul>
                </li>
                <li class="menu-list nav-active"> <a href=""><i class="fa fa-file-text"></i> <span>订单管理</span></a>
                    <ul class="child-list">
                        <li class="active"><a href="销售订单列表.html">销售订单列表</a></li>
                        <li><a href="充值订单列表.html">充值订单列表</a></li>
                        <li><a href="补货订单列表.html">补货订单列表</a></li>
                    </ul>
                </li>
                <li class="menu-list"><a href=""><i class="fa fa-shopping-cart"></i> <span>商品管理</span></a>
                    <ul class="child-list">
                        <li><a href="商品列表.html">商品列表</a></li>
                    </ul>
                </li>
                <li class="menu-list"><a href=""><i class="fa fa-desktop"></i> <span>机器管理</span></a>
                    <ul class="child-list">
                        <li><a href="机器列表.html">机器列表</a></li>
                        <li><a href="货道列表.html">货道列表</a></li>
                        <li><a href="补货预警设置.html">补货预警设置</a></li>
                    </ul>
                </li>
                <li class="menu-list"><a href="javascript:;"><i class="fa fa-pie-chart"></i> <span>数据管理</span></a>
                    <ul class="child-list">
                        <li><a href="数据统计.html">数据统计</a></li>
                    </ul>
                </li>
                <li class="menu-list"><a href=""><i class="fa fa-users"></i> <span>用户管理</span></a>
                    <ul class="child-list">
                        <li><a href="员工列表.html">员工列表</a></li>
                        <li><a href="微信接入.html">微信接入</a></li>
                        <li><a href="微信菜单.html">微信菜单</a></li>
                        <li><a href="微信支付.html">微信支付</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="body-content">
        <!-- 头部区域保持不变 -->
        <div class="header-section">
            <div class="logo dark-logo-bg"> <a href="index.html"> <img src="img/logo-icon.png" alt="">
                <span class="brand-name" style="font-size: 15px; font-weight: bold;">永辉外卖</span> </a> </div>
            <div class="icon-logo dark-logo-bg hidden-xs hidden-sm"> <a href="index.html"><img src="img/logo-icon.png" alt=""> </a> </div>
            <a class="toggle-btn"><i class="fa fa-outdent"></i></a>
            <div class="kouhao">专注健康.营养</div>
            <div class="notification-wrap">
                <div class="right-notification">
                    <ul class="notification-menu">
                        <li> <a href="javascript:;" class="btn btn-default dropdown-toggle"> <i class="fa fa-cogs"></i>账号设置 </a> </li>
                        <li> <a href="javascript:;" class="btn btn-default dropdown-toggle"> <i class="fa fa-sign-out"></i>退出登录 </a> </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 页面标题和面包屑导航 -->
        <div class="page-head">
            <ol class="breadcrumb">
                <li><a href="#">订单管理</a></li>
                <li class="active">销售订单列表</li>
            </ol>
            <h3>销售订单列表</h3>
        </div>

        <!-- 主内容区域 -->
        <div class="wrapper">
            <div class="panel">
                <div class="panel-body">
                    <!--&lt;!&ndash; 调试信息区域 &ndash;&gt;
                    <div id="debugInfo" class="alert alert-info">
                        <strong>调试信息：</strong>
                        <div>请求URL: <span id="debugUrl"></span></div>
                        <div>响应状态: <span id="debugStatus"></span></div>
                        <div>错误信息: <span id="debugError"></span></div>
                    </div>-->

                    <!-- 查询表单和新增按钮 -->
                    <div class="row m-b-20">
                        <div class="col-md-8">
                            <form id="searchForm" class="form-inline">
                                <div class="form-group m-r-10">
                                    <input type="text" class="form-control" id="searchOrderNum" placeholder="订单号">
                                </div>
                                <div class="form-group m-r-10">
                                    <input type="text" class="form-control" id="searchUserName" placeholder="用户名">
                                </div>
                                <div class="form-group m-r-10">
                                    <input type="text" class="form-control" id="searchUserPhone" placeholder="用户电话">
                                </div>
                                <div class="form-group m-r-10">
                                    <select class="form-control" id="searchStatus">
                                        <option value="">全部状态</option>
                                        <option value="pending">待付款</option>
                                        <option value="paid">已付款</option>
                                        <option value="completed">已完成</option>
                                        <option value="cancelled">已取消</option>
                                        <option value="refunded">已退款</option>
                                    </select>
                                </div>
                                <button type="button" class="btn btn-primary" id="searchBtn">
                                    <i class="fa fa-search"></i> 查询
                                </button>
                                <button type="button" class="btn btn-default" id="resetBtn">
                                    <i class="fa fa-refresh"></i> 重置
                                </button>
                            </form>
                        </div>
                        <div class="col-md-4 text-right">
                            <button class="btn btn-success" id="addOrderBtn">
                                <i class="fa fa-plus"></i> 新增订单
                            </button>
                        </div>
                    </div>

                    <!-- 批量操作区域 -->
                    <div class="batch-actions m-b-20" style="display: none;" id="batchActions">
                        <button class="btn btn-default" id="batchCancelBtn">批量取消</button>
                        <button class="btn btn-primary" id="batchCompleteBtn">批量完成</button>
                        <button class="btn btn-danger" id="batchDeleteBtn">批量删除</button>
                    </div>

                    <!-- 表格区域 -->
                    <div class="table-responsive">
                        <table class="table m-t-20">
                            <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAll"></th>
                                <th>订单号</th>
                                <th>用户ID</th>
                                <th>用户名</th>
                                <th>用户电话</th>
                                <th>商品ID</th>
                                <th>商品名称</th>
                                <th>数量</th>
                                <th>总价</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="orderTableBody">
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页区域 -->
                    <div class="page clearfix">
                        <div class="pull-left">共 <span id="totalRecords">0</span> 条记录 第 <span id="currentPage">1</span> / <span id="totalPages">1</span> 页</div>
                        <div class="pull-right">
                            <nav aria-label="..." class="pull-left">
                                <ul class="pagination" id="pagination">
                                    <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
                                    <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>
                                    <li><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>
                                </ul>
                            </nav>
                            <div class="pull-left p-r-20 p-l-20">
                                <select class="form-control" id="pageSize">
                                    <option value="10">10条每页</option>
                                    <option value="20">20条每页</option>
                                    <option value="50">50条每页</option>
                                    <option value="100">100条每页</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- 新增订单模态框 -->
                    <div class="modal fade" id="addOrderModal" tabindex="-1" role="dialog" aria-labelledby="addOrderModalLabel">
                        <div class="modal-dialog" role="document" style="width: 500px;">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="addOrderModalLabel">新增订单</h4>
                                </div>
                                <div class="modal-body">
                                    <form id="addOrderForm">
                                        <div class="form1">
                                            <ul class="row">
                                                <li class="col-xs-12"> <span>订单号：</span> <input type="text" id="orderNum" name="orderNum" class="form-control" required></li>
                                                <li class="col-xs-12"><span>用户ID：</span><input type="text" id="newUserId" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>用户姓名：</span> <input type="text" id="newUserName" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>用户手机：</span> <input type="text" id="newUserPhone" class="form-control"></li>
                                                <li class="col-xs-12"> <span>商品名称：</span> <input type="text" id="newProductName" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>商品ID：</span> <input type="text" id="newProductId" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>数量：</span> <input type="number" id="newQuantity" class="form-control" min="1" required></li>
                                                <li class="col-xs-12"> <span>总价：</span> <input type="number" id="newTotalPrice" class="form-control" min="0" step="0.01" required></li>
                                                <li class="col-xs-12"> <span>状态：</span>
                                                    <select id="newStatus" class="form-control" required>
                                                        <option value="pending">待付款</option>
                                                        <option value="paid">已付款</option>
                                                        <option value="completed">已完成</option>
                                                        <option value="cancelled">已取消</option>
                                                        <option value="refunded">已退款</option>
                                                    </select>
                                                </li>
                                            </ul>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                    <button type="button" id="saveNewOrderBtn" class="btn btn-primary">保存</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 编辑订单模态框 -->
                    <div class="modal fade" id="editOrderModal" tabindex="-1" role="dialog" aria-labelledby="editOrderModalLabel">
                        <div class="modal-dialog" role="document" style="width: 500px;">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="editOrderModalLabel">编辑订单</h4>
                                </div>
                                <div class="modal-body">
                                    <form id="editOrderForm">
                                        <input type="hidden" id="editOrderId">
                                        <div class="form1">
                                            <ul class="row">
                                                <li class="col-xs-12"> <span>订单号：</span> <input type="text" id="editOrderNo" class="form-control" disabled></li>
                                                <li class="col-xs-12"><span>用户ID：</span><input type="text" id="editUserId" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>用户姓名：</span> <input type="text" id="editUserName" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>用户手机：</span> <input type="text" id="editUserPhone" class="form-control"></li>
                                                <li class="col-xs-12"> <span>商品名称：</span> <input type="text" id="editProductName" class="form-control" required></li>
                                                <li class="col-xs-12"> <span>商品ID：</span> <input type="text" id="editProductId" class="form-control"></li>
                                                <li class="col-xs-12"> <span>数量：</span> <input type="number" id="editQuantity" class="form-control" min="1" required></li>
                                                <li class="col-xs-12"> <span>总价：</span> <input type="number" id="editTotalPrice" class="form-control" min="0" step="0.01" required></li>
                                                <li class="col-xs-12"> <span>状态：</span>
                                                    <select id="editStatus" class="form-control" required>
                                                        <option value="pending">待付款</option>
                                                        <option value="paid">已付款</option>
                                                        <option value="completed">已完成</option>
                                                        <option value="cancelled">已取消</option>
                                                        <option value="refunded">已退款</option>
                                                    </select>
                                                </li>
                                            </ul>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                                    <button type="button" id="saveEditOrderBtn" class="btn btn-primary">保存更改</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 订单详情模态框 -->
                    <div class="modal fade" id="orderDetailModal" tabindex="-1" role="dialog" aria-labelledby="orderDetailModalLabel">
                        <div class="modal-dialog modal-lg" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h4 class="modal-title" id="orderDetailModalLabel">订单详情</h4>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5>基本信息</h5>
                                            <table class="table table-bordered">
                                                <tr>
                                                    <th width="30%">订单号</th>
                                                    <td id="detailOrderNum"></td>
                                                </tr>
                                                <tr>
                                                    <th>用户姓名</th>
                                                    <td id="detailUserName"></td>
                                                </tr>
                                                <tr>
                                                    <th>用户手机</th>
                                                    <td id="detailUserPhone"></td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <h5>商品信息</h5>
                                            <table class="table table-bordered">
                                                <tr>
                                                    <th width="30%">商品名称</th>
                                                    <td id="detailProductName"></td>
                                                </tr>
                                                <tr>
                                                    <th>商品ID</th>
                                                    <td id="detailProductId"></td>
                                                </tr>
                                                <tr>
                                                    <th>数量</th>
                                                    <td id="detailQuantity"></td>
                                                </tr>
                                                <tr>
                                                    <th>总价</th>
                                                    <td id="detailTotalPrice"></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="row mt-3">
                                        <div class="col-md-12">
                                            <h5>状态信息</h5>
                                            <table class="table table-bordered">
                                                <tr>
                                                    <th width="20%">当前状态</th>
                                                    <td id="detailStatus"></td>
                                                </tr>
                                                <tr>
                                                    <th>创建时间</th>
                                                    <td id="detailCreatedAt"></td>
                                                </tr>
                                                <tr>
                                                    <th>更新时间</th>
                                                    <td id="detailUpdatedAt"></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 删除确认模态框 -->
                    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" role="dialog" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">确认删除</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <p>确定要删除此订单吗？此操作不可撤销。</p>
                                    <input type="hidden" id="deleteOrderId">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                    <button type="button" id="confirmDeleteBtn" class="btn btn-danger">确认删除</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 批量操作确认模态框 -->
                    <div class="modal fade" id="batchConfirmModal" tabindex="-1" role="dialog" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="batchModalTitle">确认操作</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <p id="batchConfirmMessage">确定要对选中的订单执行此操作吗？</p>
                                    <input type="hidden" id="batchActionType">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                    <button type="button" id="confirmBatchBtn" class="btn btn-primary">确认</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 错误信息模态框 -->
                    <div class="modal fade" id="errorModal" tabindex="-1" role="dialog" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header bg-danger text-white">
                                    <h5 class="modal-title">错误</h5>
                                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <p class="text-danger" id="errorMessage"></p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 加载动画 -->
                    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="js/bootstrap.js"></script>
<script>
    // 全局变量
    var currentPage = 1;
    var pageSize = 10;
    var baseApiUrl = 'http://localhost:8888/api/orders'; // 后端API基础URL

    // 显示调试信息
    function showDebugInfo(url, status, error) {
        $('#debugUrl').text(url);
        $('#debugStatus').text(status);
        $('#debugError').text(error || '无');
        $('#debugInfo').show();
    }

    // 显示加载动画
    function showLoading() {
        $('#loadingOverlay').show();
    }

    // 隐藏加载动画
    function hideLoading() {
        $('#loadingOverlay').hide();
    }

    // 显示错误对话框
    function showErrorDialog(message) {
        $('#errorMessage').text(message);
        $('#errorModal').modal('show');
    }

    // 显示成功提示
    function showSuccessToast(message) {
        // 这里可以替换为更美观的通知组件
        alert('成功: ' + message);
    }

    // 格式化日期时间
    function formatDateTime(timestamp) {
        if (!timestamp) return 'N/A';
        var date = new Date(timestamp);
        return date.toLocaleString();
    }

    // 获取状态样式类
    function getStatusClass(status) {
        var classes = {
            'pending': 'status-pending',
            'paid': 'status-paid',
            'completed': 'status-completed',
            'cancelled': 'status-cancelled',
            'refunded': 'status-refunded'
        };
        return classes[status] || '';
    }

    // 获取状态文本
    function getStatusText(status) {
        var texts = {
            'pending': '待付款',
            'paid': '已付款',
            'completed': '已完成',
            'cancelled': '已取消',
            'refunded': '已退款'
        };
        return texts[status] || status;
    }

    // 增强的AJAX请求
    function enhancedAjax(options) {
        var defaults = {
            url: '',
            type: 'GET',
            data: {},
            dataType: 'json',
            timeout: 10000,
            maxRetries: 2,
            retryDelay: 1000,
            beforeSend: function() {
                showLoading();
            },
            complete: function() {
                hideLoading();
            }
        };

        var settings = $.extend({}, defaults, options);
        var retryCount = 0;

        function doRequest() {
            return $.ajax(settings)
                .fail(function(xhr, status, error) {
                    if (status === 'timeout' && retryCount < settings.maxRetries) {
                        retryCount++;
                        setTimeout(doRequest, settings.retryDelay);
                    } else {
                        if (settings.error) {
                            settings.error(xhr, status, error);
                        }
                        handleAjaxError(xhr, status, error);
                    }
                });
        }

        return doRequest();
    }

    // 处理AJAX错误
    function handleAjaxError(xhr, status, error) {
        var errorMessage = '请求失败: ';

        if (status === 'timeout') {
            errorMessage += '请求超时，请检查网络连接';
        } else if (xhr.status === 404) {
            errorMessage += '请求的资源不存在';
        } else if (xhr.status === 500) {
            errorMessage += '服务器内部错误';
        } else if (xhr.status === 403) {
            errorMessage += '无权限执行此操作';
        } else {
            errorMessage += error || '未知错误';
        }

        showErrorDialog(errorMessage);

        // 记录错误日志
        console.error('AJAX Error:', {
            url: xhr.responseURL,
            status: xhr.status,
            error: error,
            timestamp: new Date().toISOString()
        });
    }

    // 加载订单数据
    function loadOrders(page) {
        var params = {
            pageNum: page,
            pageSize: pageSize,
            orderNum: $('#searchOrderNum').val(),
            userName: $('#searchUserName').val(),
            userPhone: $('#searchUserPhone').val(),
            status: $('#searchStatus').val()
        };

        enhancedAjax({
            url: baseApiUrl,
            type: 'GET',
            data: params,
            success: function(response) {
                if (response && response.code === 200) {
                    var pageInfo = response.data;
                    renderOrders(pageInfo.list);
                    updatePaginationInfo(pageInfo.total, pageInfo.pageNum, pageInfo.pageSize);
                    renderPagination(pageInfo.total, pageInfo.pageNum, pageInfo.pageSize);
                } else {
                    showErrorDialog(response.message || '获取订单列表失败');
                }
            },
            error: function(xhr, status, error) {
                showErrorDialog('加载订单列表失败: ' + error);
            }
        });
    }

    // 渲染订单数据到表格
    function renderOrders(orders) {
        var tbody = $('#orderTableBody');
        tbody.empty();

        if (!orders || orders.length === 0) {
            tbody.html('<tr><td colspan="13" class="text-center">暂无订单数据</td></tr>');
            return;
        }

        $.each(orders, function(index, order) {
            var statusClass = getStatusClass(order.status);
            var statusText = getStatusText(order.status);
            var createTime = formatDateTime(order.createdAt);
            var updateTime = formatDateTime(order.updatedAt);

            var row = '<tr>' +
                '<td><input type="checkbox" class="order-checkbox" data-id="' + order.id + '"></td>' +
                '<td>' + (order.orderNum || 'N/A') + '</td>' +
                '<td>' + (order.userId || 'N/A') + '</td>' +
                '<td>' + (order.userName || 'N/A') + '</td>' +
                '<td>' + (order.userPhone || 'N/A') + '</td>' +
                '<td>' + (order.productId || 'N/A') + '</td>' +
                '<td>' + (order.productName || 'N/A') + '</td>' +
                '<td>' + (order.quantity || 0) + '</td>' +
                '<td>' + (order.totalPrice ? order.totalPrice.toFixed(2) : '0.00') + '</td>' +
                '<td>' + createTime + '</td>' +
                '<td>' + updateTime + '</td>' +
                '<td><span class="' + statusClass + '">' + statusText + '</span></td>' +
                '<td>' +
                '<div class="btn-group">' +
                '<button class="btn btn-sm btn-info me-2 detail-btn" data-id="' + order.id + '" title="查看详情">' +
                '<i class="fa fa-eye"></i>' +
                '</button>' +
                '<button class="btn btn-sm btn-warning me-2 edit-btn" data-id="' + order.id + '" title="编辑">' +
                '<i class="fa fa-edit"></i>' +
                '</button>' +
                '<button class="btn btn-sm btn-danger delete-btn" data-id="' + order.id + '" title="删除">' +
                '<i class="fa fa-trash"></i>' +
                '</button>' +
                '</div>' +
                '</td>' +
                '</tr>';

            tbody.append(row);
        });

        // 绑定表格事件
        bindTableEvents();
    }

    // 绑定表格事件
    function bindTableEvents() {
        // 详情按钮
        $('.detail-btn').click(function() {
            var orderId = $(this).data('id');
            showOrderDetail(orderId);
        });

        // 编辑按钮
        $('.edit-btn').click(function() {
            var orderId = $(this).data('id');
            loadOrderForEdit(orderId);
        });

        // 删除按钮
        $('.delete-btn').click(function() {
            var orderId = $(this).data('id');
            showDeleteConfirm(orderId);
        });

        // 复选框
        $('.order-checkbox').change(function() {
            updateBatchActionsState();
        });

        // 全选
        $('#selectAll').change(function() {
            $('.order-checkbox').prop('checked', $(this).prop('checked'));
            updateBatchActionsState();
        });
    }

    // 更新批量操作按钮状态
    function updateBatchActionsState() {
        var checkedCount = $('.order-checkbox:checked').length;
        if (checkedCount > 0) {
            $('#batchActions').show();
            $('#batchDeleteBtn').text('批量删除(' + checkedCount + ')');
        } else {
            $('#batchActions').hide();
        }
    }

    // 显示订单详情
    function showOrderDetail(orderId) {
        var requestUrl = baseApiUrl + '/' + orderId;
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response.code === 200) {
                    var order = response.data;
                    // 填充详情模态框
                    $('#detailOrderNum').text(order.orderNum || 'N/A');
                    $('#detailUserName').text(order.userName || 'N/A');
                    $('#detailUserPhone').text(order.userPhone || 'N/A');
                    $('#detailProductName').text(order.productName || 'N/A');
                    $('#detailProductId').text(order.productId || 'N/A');
                    $('#detailQuantity').text(order.quantity || 0);
                    $('#detailTotalPrice').text(order.totalPrice ? order.totalPrice.toFixed(2) : '0.00');
                    $('#detailStatus').text(getStatusText(order.status));
                    $('#detailCreatedAt').text(formatDateTime(order.createdAt));
                    $('#detailUpdatedAt').text(formatDateTime(order.updatedAt));

                    // 显示详情模态框
                    $('#orderDetailModal').modal('show');
                } else {
                    showErrorDialog('获取订单详情失败: ' + response.message);
                    showDebugInfo(requestUrl, '响应错误', response.message);
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('加载订单详情失败: ' + errorMsg);
                showDebugInfo(requestUrl, '请求失败', errorMsg);
            }
        });
    }

    // 加载订单数据到编辑模态框
    function loadOrderForEdit(orderId) {
        var requestUrl = baseApiUrl + '/' + orderId;
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response.code === 200) {
                    var order = response.data;
                    $('#editOrderId').val(order.id);
                    $('#editOrderNo').val(order.orderNum || '');
                    $('#editUserId').val(order.userId || '');
                    $('#editUserName').val(order.userName || '');
                    $('#editUserPhone').val(order.userPhone || '');
                    $('#editProductName').val(order.productName || '');
                    $('#editProductId').val(order.productId || '');
                    $('#editQuantity').val(order.quantity || 0);
                    $('#editTotalPrice').val(order.totalPrice ? order.totalPrice.toFixed(2) : '0.00');
                    $('#editStatus').val(order.status || 'pending');

                    $('#editOrderModal').modal('show');
                } else {
                    showErrorDialog('加载订单失败: ' + response.message);
                    showDebugInfo(requestUrl, '响应错误', response.message);
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('加载订单失败: ' + errorMsg);
                showDebugInfo(requestUrl, '请求失败', errorMsg);
            }
        });
    }

    // 显示删除确认对话框
        function showDeleteConfirm(orderId) {
        $('#deleteOrderId').val(orderId);
        $('#deleteConfirmModal').modal('show');
    }

    // 更新分页信息
    function updatePaginationInfo(total, currentPage, pageSize) {
        $('#totalRecords').text(total);
        $('#currentPage').text(currentPage);
        $('#totalPages').text(Math.ceil(total / pageSize));
    }

    // 渲染分页控件
    function renderPagination(total, currentPage, pageSize) {
        var pagination = $('#pagination');
        pagination.empty();

        var totalPages = Math.ceil(total / pageSize);
        var maxVisiblePages = 5; // 最多显示5个页码
        var startPage, endPage;

        if (totalPages <= maxVisiblePages) {
            startPage = 1;
            endPage = totalPages;
        } else {
            var maxPagesBeforeCurrent = Math.floor(maxVisiblePages / 2);
            var maxPagesAfterCurrent = Math.ceil(maxVisiblePages / 2) - 1;

            if (currentPage <= maxPagesBeforeCurrent) {
                startPage = 1;
                endPage = maxVisiblePages;
            } else if (currentPage + maxPagesAfterCurrent >= totalPages) {
                startPage = totalPages - maxVisiblePages + 1;
                endPage = totalPages;
            } else {
                startPage = currentPage - maxPagesBeforeCurrent;
                endPage = currentPage + maxPagesAfterCurrent;
            }
        }

        // 上一页按钮
        var prevDisabled = currentPage === 1 ? 'disabled' : '';
        pagination.append(
            '<li class="page-item ' + prevDisabled + '">' +
            '<a class="page-link" href="#" aria-label="Previous" data-page="' + (currentPage - 1) + '">' +
            '<span aria-hidden="true">&laquo;</span>' +
            '</a>' +
            '</li>'
        );

        // 页码按钮
        for (var i = startPage; i <= endPage; i++) {
            var active = i === currentPage ? 'active' : '';
            pagination.append(
                '<li class="page-item ' + active + '">' +
                '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                '</li>'
            );
        }

        // 下一页按钮
        var nextDisabled = currentPage === totalPages ? 'disabled' : '';
        pagination.append(
            '<li class="page-item ' + nextDisabled + '">' +
            '<a class="page-link" href="#" aria-label="Next" data-page="' + (currentPage + 1) + '">' +
            '<span aria-hidden="true">&raquo;</span>' +
            '</a>' +
            '</li>'
        );

        // 绑定分页点击事件
        $('.page-link').click(function(e) {
            e.preventDefault();
            var page = $(this).data('page');
            if (page && page !== currentPage) {
                currentPage = page;
                loadOrders(currentPage);
            }
        });
    }

    // 创建新订单
    function createOrder() {
        var orderDTO = {
            orderNum: $('#orderNum').val(),
            userId: $('#newUserId').val(),
            userName: $('#newUserName').val(),
            userPhone: $('#newUserPhone').val(),
            productId: $('#newProductId').val(),
            productName: $('#newProductName').val(),
            quantity: parseInt($('#newQuantity').val()),
            totalPrice: parseFloat($('#newTotalPrice').val()),
            status: $('#newStatus').val()
        };

        if (!validateOrderForm(orderDTO)) {
            return;
        }

        var requestUrl = baseApiUrl;
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(orderDTO),
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response.code === 200) {
                    $('#addOrderModal').modal('hide');
                    $('#addOrderForm')[0].reset();
                    showSuccessToast('订单创建成功');
                    loadOrders(currentPage);
                } else {
                    showErrorDialog('创建订单失败: ' + response.message);
                    showDebugInfo(requestUrl, '响应错误', response.message);
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('创建订单失败: ' + errorMsg);
                showDebugInfo(requestUrl, '请求失败', errorMsg);
            }
        });
    }

    // 更新订单
    function updateOrder() {
        var orderId = $('#editOrderId').val();
        var orderDTO = {
            orderNum: $('#editOrderNo').val(),
            userId: $('#editUserId').val(),
            userName: $('#editUserName').val(),
            userPhone: $('#editUserPhone').val(),
            productName: $('#editProductName').val(),
            productId: $('#editProductId').val(),
            quantity: parseInt($('#editQuantity').val()),
            totalPrice: parseFloat($('#editTotalPrice').val()),
            status: $('#editStatus').val()
        };

        if (!validateOrderForm(orderDTO)) {
            return;
        }

        var requestUrl = baseApiUrl + '/' + orderId;
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(orderDTO),
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response && response.code === 200) {  // 确保response存在且有code属性
                    $('#editOrderModal').modal('hide');
                    showSuccessToast('订单更新成功');
                    loadOrders(currentPage);
                } else {
                    showErrorDialog(response ? response.message : '未知错误');
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('更新订单失败: ' + errorMsg);
            }
        });
    }

    // 删除订单
    function deleteOrder() {
        var orderId = $('#deleteOrderId').val();
        var requestUrl = baseApiUrl + '/' + orderId;
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            type: 'DELETE',
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response.code === 200) {
                    $('#deleteConfirmModal').modal('hide');
                    showSuccessToast('订单删除成功');
                    loadOrders(currentPage);
                } else {
                    showErrorDialog('删除订单失败: ' + response.message);
                    showDebugInfo(requestUrl, '响应错误', response.message);
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('删除订单失败: ' + errorMsg);
                showDebugInfo(requestUrl, '请求失败', errorMsg);
            }
        });
    }

    // 批量操作订单
    function batchUpdateOrders(action) {
        var orderIds = [];
        $('.order-checkbox:checked').each(function() {
            orderIds.push($(this).data('id'));
        });

        if (orderIds.length === 0) {
            showErrorDialog('请至少选择一条订单');
            return;
        }

        var requestUrl = baseApiUrl + '/batch-update';
        showDebugInfo(requestUrl, '请求中...', '');

        enhancedAjax({
            url: requestUrl,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                ids: orderIds,
                action: action
            }),
            success: function(response) {
                showDebugInfo(requestUrl, '200 成功', '');
                if (response.code === 200) {
                    $('#batchConfirmModal').modal('hide');
                    showSuccessToast('批量操作成功');
                    loadOrders(currentPage);
                } else {
                    showErrorDialog('批量操作失败: ' + response.message);
                    showDebugInfo(requestUrl, '响应错误', response.message);
                }
            },
            error: function(xhr, status, error) {
                var errorMsg = '状态: ' + xhr.status + ', 错误: ' + error;
                showErrorDialog('批量操作失败: ' + errorMsg);
                showDebugInfo(requestUrl, '请求失败', errorMsg);
            }
        });
    }

    // 验证订单表单
    function validateOrderForm(order) {
        if (!order.orderNum || order.orderNum.trim() === '') {
            showErrorDialog('请输入订单号');
            return false;
        }

        if (!order.userName || order.userName.trim() === '') {
            showErrorDialog('请输入用户姓名');
            return false;
        }

        if (!order.productName || order.productName.trim() === '') {
            showErrorDialog('请输入商品名称');
            return false;
        }

        if (!order.quantity || order.quantity <= 0) {
            showErrorDialog('请输入有效的数量');
            return false;
        }

        if (!order.totalPrice || order.totalPrice <= 0) {
            showErrorDialog('请输入有效的总价');
            return false;
        }

        if (!order.status) {
            showErrorDialog('请选择订单状态');
            return false;
        }

        return true;
    }

    // 页面加载完成后执行
    $(document).ready(function() {
        // 加载订单数据
        loadOrders(currentPage);

        // 分页大小改变事件
        $('#pageSize').change(function() {
            pageSize = $(this).val();
            currentPage = 1;
            loadOrders(currentPage);
        });

        // 查询按钮点击事件
        $('#searchBtn').click(function() {
            currentPage = 1;
            loadOrders(currentPage);
        });

        // 重置按钮点击事件
        $('#resetBtn').click(function() {
            $('#searchForm')[0].reset();
            currentPage = 1;
            loadOrders(currentPage);
        });

        // 新增订单按钮点击事件
        $('#addOrderBtn').click(function() {
            $('#addOrderModal').modal('show');
        });

        // 保存新增订单按钮点击事件
        $('#saveNewOrderBtn').click(function() {
            createOrder();
        });

        // 保存编辑订单按钮点击事件
        $('#saveEditOrderBtn').click(function() {
            updateOrder();
        });

        // 确认删除按钮点击事件
        $('#confirmDeleteBtn').click(function() {
            deleteOrder();
        });

        // 批量操作按钮事件
        $('#batchCancelBtn').click(function() {
            $('#batchActionType').val('cancel');
            $('#batchModalTitle').text('确认取消订单');
            $('#batchConfirmMessage').text('确定要取消选中的订单吗？');
            $('#batchConfirmModal').modal('show');
        });

        $('#batchCompleteBtn').click(function() {
            $('#batchActionType').val('complete');
            $('#batchModalTitle').text('确认完成订单');
            $('#batchConfirmMessage').text('确定要将选中的订单标记为已完成吗？');
            $('#batchConfirmModal').modal('show');
        });

        $('#batchDeleteBtn').click(function() {
            $('#batchActionType').val('delete');
            $('#batchModalTitle').text('确认删除订单');
            $('#batchConfirmMessage').text('确定要删除选中的订单吗？此操作不可撤销。');
            $('#batchConfirmModal').modal('show');
        });

        // 确认批量操作按钮
        $('#confirmBatchBtn').click(function() {
            var action = $('#batchActionType').val();
            batchUpdateOrders(action);
        });
    });
</script>
</body>
</html>